import { defineStore } from 'pinia'
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

export const useUserStore = defineStore('user', () => {
  const router = useRouter()
  const token = ref('')
  const username = ref('')
  const isAdmin = ref(false)

  const login = async (credentials) => {
    try {
      const response = await fetch('http://localhost:5000/api/auth/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(credentials)
      })

      if (!response.ok) {
        const errorData = await response.json()
        throw new Error(errorData.error || '登录失败')
      }

      const data = await response.json()
      token.value = 'authenticated'  // 实际项目中应该使用JWT token
      username.value = data.user.username
      isAdmin.value = data.user.username === 'admin'  // 根据实际业务逻辑调整
      ElMessage.success(data.message)
    } catch (error) {
      ElMessage.error(error.message)
      throw error
    }
  }

  const register = async (credentials) => {
    try {
      const response = await fetch('http://localhost:5000/api/auth/register', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(credentials)
      })

      if (!response.ok) {
        const errorData = await response.json()
        throw new Error(errorData.error || '注册失败')
      }

      const data = await response.json()
      ElMessage.success(data.message)
      // 注册成功后自动登录
      await login(credentials)
    } catch (error) {
      ElMessage.error(error.message)
      throw error
    }
  }

  const logout = () => {
    token.value = ''
    username.value = ''
    isAdmin.value = false
    router.push('/login')
  }

  const changePassword = async (data) => {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        if (data.newPassword !== data.confirmPassword) {
          reject(new Error('两次输入密码不一致'))
        } else {
          ElMessage.success('密码修改成功')
          resolve()
        }
      }, 500)
    })
  }

  return {
    token,
    username,
    isAdmin,
    login,
    logout,
    changePassword,
    register
  }
})
